#pragma once

#include <iostream>
#include <string>
#include <sys/stat.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "log.hpp"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

class TcpClient
{
public:
    TcpClient(const std::string& serverip,const uint16_t& port)
    :_serverip(serverip),_port(port),_sock(-1)
    {

    }

    void initClient()
    {
        _sock = socket(AF_INET,SOCK_STREAM,0);
        if(_sock < 0)
        {
            std::cerr << "socket create error" <<std::endl;
            exit(2);
        }
    }

    void start()
    {
        struct sockaddr_in server;
        memset(&server,0,sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = inet_addr(_serverip.c_str());

        if(connect(_sock,(struct sockaddr*)&server,sizeof(server)) != 0)
        {
            std::cerr << "connect error" <<std::endl;
        }
        else
        {
            std::string msg;
            while(1)
            {
                std::cout<<"Enter# ";
                std::getline(std::cin,msg);
                write(_sock,msg.c_str(),msg.size());

                char buffer[1024];
                int n = read(_sock,buffer,sizeof(buffer)-1);
                if(n > 0)
                {
                    buffer[n] = 0;
                    std::cout<<"server say: "<<buffer<<std::endl;
                }
                else
                {
                    break;
                }
            }
        }
    }

    ~TcpClient()
    {
        if(_sock >= 0)
        {
            close(_sock);
        }
    }

private:
    int _sock;
    std::string _serverip;
    uint16_t _port;
};
